using System.ComponentModel;
using ModelContextProtocol.Server;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RevitCopilot.MCPServer.Models;
using RevitCopilot.MCPServer.Services;

namespace RevitCopilot.MCPServer.Tools;

[McpServerToolType]
public sealed class DeleteTool
{
    [McpServerTool,Description("通过Revit元素的ElementID删除元素")]
    public static object DeleteElements([Description("要删除的Revit元素ID列表")] IList<string> elementIds,
        SocketService socketService)
    {
        try
        {
            // 连接到Revit插件服务端
            if (!socketService.Connect())
            {
                return new { type = "text", text = "MCP Tool无法连接到Revit插件服务端" };
            }
            // 创建JObject对象包装elementIds参数
            var parametersObject = new JObject();
            parametersObject["elementIds"] = JArray.FromObject(elementIds);
            // 发送方法名和参数
            bool sendSuccess = socketService.SendRequest("DeleteElements", parametersObject);
            if (!sendSuccess)
            {
                return new { type = "text", text = "MCP Tool发送删除元素请求失败" };
            }
            // 接收执行结果
            var response = socketService.ReceiveResponse<JsonRpcResponse>();
            if (response != null)
            {
                // 返回成功响应，包含Revit返回的标准JSON-RPC结果
                return new { type = "text",
                            text = JsonConvert.SerializeObject(response, Formatting.Indented) };
            }
            else
            {
                return new { type = "text", text = "MCP Tool未收到Revit插件服务端方法执行结果响应" };
            }
        }
        catch (Exception ex)
        {
            return new { type = "text", text = $"MCP Tool执行过程中发生错误: {ex.Message}" };
        }
        finally
        {
            // 最后无论是否收到响应都要关闭，销毁客户端的Socket连接
            // 不在这里关闭连接，由依赖注入容器管理SocketService的生命周期
        }
    }
}